﻿using IdentityModel.Client;
using Newtonsoft.Json.Linq;
using System.Net;
using Microsoft.AspNetCore.SignalR.Client;

await GetTokenAndCallApiAsync();

static async Task GetTokenAndCallApiAsync()
{
    // discover endpoints from metadata
    var client = new HttpClient();
    var config = new DiscoveryDocumentRequest()
    {
        Address = "http://host.docker.internal:7010",
        Policy = new DiscoveryPolicy()
        {
            RequireHttps = false
        }
    };
    var disco = await client.GetDiscoveryDocumentAsync(config);
    if (disco.IsError)
    {
        Console.WriteLine(disco.Error);
        return;
    }

    var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
    {
        Address = disco.TokenEndpoint,

        ClientId = "consoleclient",
        ClientSecret = "secret1",
        Scope = "poemapi"
    });

    if (tokenResponse.IsError)
    {
        Console.WriteLine(tokenResponse.Error);
        return;
    }

    Console.WriteLine(tokenResponse.Json);
    Console.WriteLine("Api启动后按回车......");
    Console.ReadLine();
    // call api
    var apiClient = new HttpClient();
    apiClient.SetBearerToken(tokenResponse.AccessToken);

    var response = await apiClient.GetAsync("http://host.docker.internal:5189/api/Game/GetPlayerByUserName?name=admin");
    if (!response.IsSuccessStatusCode)
    {
        Console.WriteLine(response.StatusCode);
        Console.WriteLine(await response.Content.ReadAsStringAsync());
    }
    else
    {
        var content = await response.Content.ReadAsStringAsync();
        Console.WriteLine(content);
    }

    Console.ReadLine();

    var connection = new HubConnectionBuilder()
        .WithUrl("http://host.docker.internal:5189/singlegamehub", options =>
        {
            options.AccessTokenProvider = () => Task.FromResult(tokenResponse.AccessToken);
        })
        .Build();

    connection.Closed += async (error) =>
    {
        await Task.Delay(new Random().Next(0, 5) * 1000);
        await connection.StartAsync();
    };

    connection.On<string>("PlayerExist", (user) =>
    {
       Console.WriteLine("用户存在:"+user);
    });

    connection.On<string>("PlayerNotExist", (user) =>
    {
        Console.WriteLine("用户不存在:" + user);
    });

    try
    {
        await connection.StartAsync();
        await connection.InvokeAsync("CheckUser","admin");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    Console.ReadLine();
}
